/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.staff.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.StaffException;
import com.pitop.core.tools.RegExpUtils;
import com.pitop.staff.dao.StaffDAO;
import com.pitop.staff.entity.Staff;
import com.pitop.staff.entity.StaffState;
import com.pitop.sync.dao.SyncNewDataDAO;
import com.pitop.sync.entity.SyncNewDataEventState;
import com.pitop.sync.entity.SyncNewDataState;
import com.pitop.sync.entity.SyncTraceModel;
import com.pitop.sync.service.SyncNewDataSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("staffSV")
@Slf4j
public class StaffSVImpl extends BaseSVImpl<Staff, Long> implements StaffSV {

    @Autowired
    private StaffDAO staffDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Autowired
    private SyncNewDataDAO syncNewDataDAO;

    @Autowired
    private SyncNewDataSV syncNewDataSV;


    @Override
    protected BaseDAO getBaseDAO() {
        return staffDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(Staff entity) throws BaseException {
        entity.setCode(String.valueOf(uidGenerator.getUID()));
//      状态 入职 hire，离职 leave,新增默认为入职 hire
        entity.setState(StaffState.Hire.name());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setVer(1);

        super.save(entity);
        Staff staff = staffDAO.loadByCode(entity.getCode());
        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Insert.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }

    /**
     * 数据更新
     *
     * @param staff
     * @throws BaseException
     */
    @Override
    public void modify(Staff staff) throws BaseException {
        Staff oldStaff = loadByCode(staff.getCode());
        int oldVer = oldStaff.getVer();
        staff.setVer(oldVer + 1);
        staff.setUpdateTime(new Date());
        Map<String, Object> paraMap = JSON.parseObject(JSON.toJSONString(staff, SerializerFeature.WriteDateUseDateFormat));
        paraMap.put("oldVer", oldVer);

//        if (!oldStaff.getJobnumber().equals(staff.getJobnumber())) {
//                Staff staffJobNumber = staffDAO.loadStaffByJobNumber(staff.getJobnumber());
//                if (staffJobNumber != null) {
//                    throw new StaffException(BaseException.BaseExceptionEnum.Exists);
//                }
//        }

//        if (StringUtils.isNotBlank(staff.getPhone()) && !oldStaff.getPhone().equals(staff.getPhone())) {
//            if (!RegExpUtils.checkPhone(staff.getPhone())) {
//                //表示手机好格式不正确
//                throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
//            }
//            Map<String, Object> paramPhoneMap = new HashMap<>();
//            paramPhoneMap.put("phone", staff.getPhone());
//            Staff staffPhone = staffDAO.load(paramPhoneMap);
//            if (staffPhone != null) {
//                throw new StaffException(BaseException.BaseExceptionEnum.Exists);
//            }
//        }
        getBaseDAO().update(paraMap);
        staff = loadByCode(staff.getCode());
        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Update.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }

    /**
     * 加载一个对象Staff
     *
     * @param id * @param code 唯一编码
     * @return Staff
     */
    @Override
    public Staff load(java.lang.Long id, java.lang.String code) {
        if (id == null && code == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return staffDAO.load(param);
    }

    /**
     * 加载一个对象Staff 通过id
     *
     * @param id
     * @return Staff
     */
    @Override
    public Staff loadById(java.lang.Long id) {
        if (id == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return staffDAO.loadById(id);
    }

    /**
     * 加载一个对象Staff 通过code
     *
     * @param code 唯一编码
     * @return Staff
     */
    @Override
    public Staff loadByCode(java.lang.String code) {
        if (code == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return staffDAO.loadByCode(code);
    }


    /**
     * 根据主键id,oldStates 共同更新 Staff 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(java.lang.Long id, StaffState newState, StaffState... oldStates) {
        if (id == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        staffDAO.updateStateById(id, newState.name(), states);

        Staff staff = staffDAO.loadById(id);
        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Update.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }

    /**
     * 根据主键code,oldStates 共同更新 Staff 的状态到newState状态
     *
     * @param code      唯一编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(java.lang.String code, StaffState newState, StaffState... oldStates) {
        if (code == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        staffDAO.updateStateByCode(code, newState.name(), states);

        Staff staff = staffDAO.loadByCode(code);
        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Update.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }

    /**
     * 根据主键id 更新 Staff 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(java.lang.Long id, StaffState state) {
        if (id == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        staffDAO.updateById(id, state.name());

        Staff staff = staffDAO.loadById(id);
        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Update.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }

    /**
     * 根据主键code 更新 Staff 的状态到另一个状态
     *
     * @param code  唯一编码
     * @param state 状态
     */
    @Override
    public void updateByCode(java.lang.String code, StaffState state) {
        if (code == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        staffDAO.updateByCode(code, state.name());

        Staff staff = staffDAO.loadByCode(code);
        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Update.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }


    /**
     * 删除对象Staff
     *
     * @param id * @param code 唯一编码
     * @return Staff
     */
    @Override
    public void delete(java.lang.Long id, java.lang.String code) {
        if (id == null && code == null) {
            throw new StaffException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Staff staff = new Staff();
        if (code != null) {
            staff = staffDAO.loadByCode(code);
        }
        if (id != null) {
            staff = staffDAO.loadById(id);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        staffDAO.delete(param);

        if (staff != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(staff.getFactoryCode(), SyncTraceModel.Staff.name(), SyncNewDataEventState.Delete.name(), staff.getCode(), 1, SyncNewDataState.Ready.name());
        }
    }


    /**
     * 查询Staff分页
     *
     * @param staff  对象
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Staff>
     */
    @Override
    public List<Staff> list(Staff staff, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (staff != null) {
            map = JSON.parseObject(JSON.toJSONString(staff, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        map.put("sortColumns", " code desc ");
        return staffDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(Staff staff) {
        Map<String, Object> map;
        if (staff != null) {
            map = JSON.parseObject(JSON.toJSONString(staff, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return staffDAO.count(map);
    }

    /**
     * 查询Staff分页
     *
     * @param id     * @param code  唯一编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Staff>
     */
    @Override
    public List<Staff> list(java.lang.Long id, java.lang.String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return staffDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(java.lang.Long id, java.lang.String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return staffDAO.count(param);
    }

    /**
     * 根据员工号和姓名模糊查询
     *
     * @param jobNumber   员工号
     * @param name        员工姓名
     * @param factoryCode 工厂CODE
     * @param rowStart    起始页
     * @param pageSize    每页显示条数
     * @return List<Staff>
     */
    @Override
    public List<Staff> listByJobNumberAndNameAndFactoryCode(String jobNumber, String name, String factoryCode, Integer rowStart, Integer pageSize) {
        if (rowStart < 0) {
            rowStart = 0;
        }
        if (pageSize < 0) {
            pageSize = Page.limit;
        }
        Map<String, String> paraMap = new HashMap<>();
        if (StringUtils.isNotBlank(jobNumber)) {
            paraMap.put("jobNumber", "%" + jobNumber + "%");
        }
        if (StringUtils.isNotBlank(name)) {
            paraMap.put("name", "%" + name + "%");
        }
        if (StringUtils.isNotBlank(factoryCode)) {
            paraMap.put("factoryCode", factoryCode);
        }
        return staffDAO.listByJobNumberAndNameAndFactoryCode(paraMap, new RowBounds(rowStart, pageSize));
    }

    @Override
    public Integer countByJobNumberAndNameAndFactroyCode(String jobNumber, String name, String factoryCode) {
        Map<String, String> paraMap = new HashMap<String, String>();
        if (StringUtils.isNotBlank(jobNumber)) {
            paraMap.put("jobNumber", "%" + jobNumber + "%");
        }
        if (StringUtils.isNotBlank(name)) {
            paraMap.put("name", "%" + name + "%");
        }
        if (StringUtils.isNotBlank(factoryCode)) {
            paraMap.put("factoryCode", factoryCode);
        }
        return staffDAO.countByJobNumberAndNameAndFactroyCode(paraMap);
    }

    /**
     * 根据员工号查询staff
     *
     * @param jobNumber 员工号
     * @return Staff
     */
    @Override
    public Staff loadStaffByJobNumber(String jobNumber) {
        return staffDAO.loadStaffByJobNumber(jobNumber);
    }

    /**
     * 根据员工号和工厂编码查询staff
     *
     * @param jobNumber   员工号
     * @param factoryCode 工厂编码
     * @return Staff
     */
    @Override
    public Staff loadStaffByJobNumberAndFactoryCode(String jobNumber, String factoryCode) {
        return staffDAO.loadStaffByJobNumberAndFactoryCode(jobNumber, factoryCode);
    }


}
